<template>
  <div class="about">
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>
    <el-form @submit.native.prevent="save">
      <!-- 所属分类指向一个文章的二级分类 一篇文章可以属于多个分类 -可多选-定义模型的时候就要用到数组来定义了-->
      <el-form-item label="所属分类">
        <el-select v-model="model.parent" multiple>
          <el-option
            v-for="item in parent"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题" >
        <el-input v-model="model.name" ></el-input
      ></el-form-item>
      <!-- 在文章内容这里要实现的效果不只是简单的文本展示还要有富文本的内容 -->
      <!-- 引用组件vue2-editer -->
      <!-- 原理是复制的格式文本为加了html标签的格式 而html标签是string格式-->
      <!-- 本地图片直接以二进制代码存储   但是很占用内存 加载接口很慢 -->
      <el-form-item label="文章内容" >
      </el-form-item>
      <el-form-item  >
        <vue-editor v-model="model.body"  useCustomImageHandler @image-added="handleImageAdded" >  </vue-editor>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//加括号是结构的方式，意思是直接获取里面的Vue2Editor对象
//等同于  import a from 'vue2-editor'     a.VueEditor
import { VueEditor } from "vue2-editor";
export default {

  name: "ArticlesEdit",
  props: {
    id: {},
  },
  //使用子组件
  //使用之后要使用rditor变成了子组件的使用形式即<vue-editor></vue-editor>
  components: { VueEditor },
  data() {
    return {
      model: {},
      parent: [],
      data1: [],
    };
  },
  methods: {
    async save() {
      let res;
      if (this.id) {
        res = await this.$http1.put(`rest/articles/${this.id}`, this.model);
      } else {
        res = await this.$http1.post("rest/articles", this.model);
      }
      console.log(res);
      this.$router.push("/articles/list");
      this.$message({ type: "success", message: "保存成功" });
    },
    async fech() {
      const res = await this.$http1.get(`rest/articles/${this.id}`);
      this.model = res.data;
    },
    async parentfech() {
      //这里要查找的是来自新闻的二级分类然后存在parent中
      const res = await this.$http1.get("rest/categories");
      this.data1 = res.data;
      for (var i = 0; i < this.data1.length; i++) {
        if (this.data1[i].parent != null)
          if (this.data1[i].parent._id === "625393a905333d0dd2b12b71")
            this.parent.push(this.data1[i]);
      }
    },
    async handleImageAdded(file, Editor,cursorLocation,restUploader){
      const forData=new FormData();
      forData.append("file",file);
      const res=await this.$http1.post('upload',forData);
      Editor.insertEmbed(cursorLocation,'image',res.data.url)
      restUploader();
    }
  },
  created() {
    this.id && this.fech();
    this.parentfech();
  },
};
</script>

<style>
</style>